const Router = require("koa-router")
const ResBody = require("../struct/ResBody")
const Sequelize = require('sequelize');

const { Cate, Goods, GoodsAttrConfig, GoodsAttrValue, GoodsAttr, Building, User, Room, Floor } = require("../model")
const { GoodsController, BuildingController } = require("../controller")
const router = new Router()
const utils = require("../utils/index.js");
const { bulkCreateGoodsAttr } = require("../controller/goods_controller");

const skuInitData = data => {
  let skuItem = {
    cost_price: data?.cost_price || '',
    goods_id: data?.goods_id || '',
    goods_name: data?.goods_name || '',
    image: data?.image,
    price: data?.price,
    sales: data?.sales,
    sku: data?.sku,
    sort: data?.sort,
    stock: data?.stock || 0,
    store_house_id: data?.store_house_id,
    volume: data?.volume,
    weight: data?.weight,
    cordon: data?.cordon || 0
    // id: data?.id || '',
  }
  if (data?.id) {
    skuItem.id = data.id
  }
  return skuItem;
}

// 添加商品分类；
router.post("/addCate", async ctx => {
  console.log('addCate--%s--%s==', JSON.stringify(ctx.request.body), JSON.stringify(ctx.state.user));
  const { role } = ctx.state.user;
  const store_id = ctx.header.storeid;

  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { cat_id, cat_name, sort } = ctx.request.body
  utils.checkParams({ cat_name, sort, store_id })
  let res;
  try {
    const cate = await Cate.create({ cat_name, sort, store_id, parent_id: 0, data_flag: '' });
    console.log('addCate--res: %s==', JSON.stringify(res));
    res = {
      code: 200,
      data: cate
    };
  } catch(err) {
    console.log('addCate--err: %s==', JSON.stringify(err));
    const { name, errors } = err;
    res = {
      code: 500,
      msg: ''
    };
    if (name === 'SequelizeUniqueConstraintError') {
      if (errors && errors.length) {
        if (errors[0].message === 'cat_name must be unique') {
          res.msg = `【${cat_name}】该分类已存在`
        }
      }
    }
  }
  ctx.body = new ResBody(res)
})
// 商品分类更新
router.post("/cateUpdata", async ctx => {
  console.log('cateUpdata--%s--%s==', JSON.stringify(ctx.request.body), JSON.stringify(ctx.state.user));
  const { role } = ctx.state.user;
  const store_id = ctx.header.storeid;

  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { cat_id, cat_name, sort } = ctx.request.body
  utils.checkParams({ cat_name, sort })
  let res;
  try {
    res = await Cate.update( { cat_name, sort }, { where: { cat_id } });
    console.log('cateUpdata--res: %s==', JSON.stringify(res));
  } catch(err) {
    console.log('cateUpdata--err: %s==', JSON.stringify(err));
    const { name, errors } = err;
    res = {
      code: 500,
      msg: '更新失败'
    };
    if (name === 'SequelizeUniqueConstraintError') {
      if (errors && errors.length) {
        if (errors[0].message === 'cat_name must be unique') {
          res.msg = `【${cat_name}】该分类已存在`
        }
      }
    }
  }
  ctx.body = new ResBody(res)
})
router.get("/cateDetail", async ctx => {
  console.log('cateDetail--%s--%s==', JSON.stringify(ctx.request.body), JSON.stringify(ctx.state.user));
  const store_id = ctx.header.storeid;
  const { cat_id } = ctx.request.query
  utils.checkParams({ cat_id })
  let res;
  try {
    res = await Cate.findByPk(cat_id)
    console.log('cateDetail--res: %s==', JSON.stringify(res));
  } catch(err) {
    console.log('cateDetail--err: %s==', JSON.stringify(err));
  }
  ctx.body = new ResBody({ data: res })
})
// 商品分类列表；
router.get("/cate", async ctx => {
  const cate = await Cate.findAll({ order: [['sort', 'ASC']] })
  ctx.body = new ResBody({ data: { list: cate } })
})
// 商品列表
router.get("/index", async ctx => {
  console.log('goods_index--%s===', JSON.stringify(ctx.state));
  const store_id = ctx.header.storeid;
  const goods = await GoodsController.getStoreGoods(store_id);
  console.log('goods==%s==', JSON.stringify(goods));
  ctx.body = new ResBody({ data: { list: goods?.list || [], count: goods?.count || 0 } })
})
// 商品详情
router.get("/detail", async ctx => {
  // console.log('goods_index--%s===', JSON.stringify(ctx));
  const store_id = ctx.header.storeid;
  const { id } = ctx.request.query

  const goods = await GoodsController.getStoreGoodsDetail(id);
  console.log('detail==%s==', goods);
  if (!goods) {
    return ctx.body = new ResBody({ data: '未找到该商品', code: 500, msg: '未找到该商品' })
  }
  ctx.body = new ResBody({ data: goods })
})
// 添加商品；
router.post("/add", async ctx => {
  const { role } = ctx.state.user
  const store_id = ctx.header.storeid;
  console.log('store_id==%s==', store_id);
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_name, full_goods_name, cat_id, attr = '', stock = '0', sales = '0', unit_name, unit_name2 = '', unit_convert = 1, unit_convert2 = 1, weight = 0, desc = '', sort = 500, is_hot = 0, is_recommend = 0, status = 1, is_delete = 0, slider_image = '', content } = ctx.request.body
  utils.checkParams({ goods_name, full_goods_name, unit_name, cat_id, stock, unit_name2, unit_convert, unit_convert2 })

  const goods = GoodsController.createGoods({ ...ctx.request.body, store_id })
  // const goods = await Goods.findOrCreate({ where: { goods_name, full_goods_name, store_id }, defaults: { goods_name, full_goods_name, cat_id, attr, stock, sales, unit_name, unit_name2, unit_convert, unit_convert2, weight, desc, sort, store_id, is_hot, is_recommend, status, is_delete, slider_image, content } })
  console.log('goods--typeof(goods):%s==', typeof (goods), JSON.stringify(goods));
  ctx.body = new ResBody({ data: goods })
})
// 添加商品；
router.post("/update", async ctx => {
  const { role } = ctx.state.user
  const store_id = ctx.header.storeid;
  console.log('store_id==%s==', store_id);
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_name, full_goods_name, cat_id, attr = '', stock = '0', sales = '0', unit_name, unit_name2 = '', unit_convert = 1, unit_convert2 = 1, weight = 0, desc = '', sort = 500, is_hot = 0, is_recommend = 0, status = 1, is_delete = 0, slider_image = '', content } = ctx.request.body
  utils.checkParams({ goods_name, full_goods_name, unit_name, cat_id, stock, unit_name2, unit_convert, unit_convert2 })

  const res = await GoodsController.updateGoods({ ...ctx.request.body, store_id })
  // const goods = await Goods.findOrCreate({ where: { goods_name, full_goods_name, store_id }, defaults: { goods_name, full_goods_name, cat_id, attr, stock, sales, unit_name, unit_name2, unit_convert, unit_convert2, weight, desc, sort, store_id, is_hot, is_recommend, status, is_delete, slider_image, content } })
  console.log('goods/update--typeof(res):%s==', typeof (res), JSON.stringify(res));
  ctx.body = new ResBody(res)
})

// 添加商品规格
router.post("/addAttrValue", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id, attr_list } = ctx.request.body;
  const payload = skuInitData(ctx.request.body);
  console.log('addAttrValue--payload--%s==', JSON.stringify(payload));
  
  const attrResult = GoodsAttrValue.bulkCreate([ payload ]);
  console.log('addAttrValue--attrResult--%s==', JSON.stringify(attrResult));

  ctx.body = new ResBody({ data: '', code: 200, msg: '操作成功' })
})

// 修改商品规格
router.post("/updateAttrValue", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id, sku } = ctx.request.body;
  utils.checkParams({ id, sku });
  const params = skuInitData(ctx.request.body)
  console.log('updateAttrValue--params: %s==', JSON.stringify(params));
  
  const res = await GoodsAttrValue.update({ ...ctx.request.body }, { where: { id } })
  console.log('updateAttrValue--res--%s==', res);
  ctx.body = new ResBody({ data: '', code: 200, msg: '操作成功' })
})

// 修改商品规格(废弃)
router.post("/updateAttrValue2", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_id, attr_list } = ctx.request.body
  const list = attr_list.map(d => {
    d.goods_id = goods_id;
    return d;
  })
  console.log('updateAttrValue--goods_id: %s--attr_list: %s==', goods_id, JSON.stringify(list));
  GoodsAttrValue.bulkCreate(list, { updateOnDuplicate: ["price", "retail_price", "cost_price", "stock", "weight", "code", "sort"] })
    .then(res => {
      console.log('updateAttrValue--res: %s==', JSON.stringify(res));
    })
    .catch(err => {
      console.log('updateAttrValue--err: %s==', JSON.stringify(err));
    })

  ctx.body = new ResBody({ data: '', code: 200, msg: '操作成功' })
  return;

  utils.checkParams({ goods_id })

  const findData = await GoodsAttrConfig.findOrCreate({ where: { goods_id, store_id }, defaults: { goods_id, store_id, config } })
  console.log('findData--%s==', JSON.stringify(findData));
  if (!findData[1]) {
    const res = await GoodsAttrConfig.update(
      { config }, {
      where: { goods_id, store_id }
    })
    console.log('GoodsAttrConfig.update--res--%s==', res);
    return ctx.body = new ResBody({ data: res, code: 200, msg: '操作成功' })
  }
  ctx.body = new ResBody({ data: findData, code: 200, msg: '操作成功' })
})

// 添加商品规格配置 attr_config；
router.post("/updateAttrConfig", async ctx => {
  console.log('updateAttrConfig--ctx.header--%s==', JSON.stringify(ctx.header));
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id: goods_id, attr_list } = ctx.request.body
  utils.checkParams({ goods_id })

  // findData[1]：找到已有记录为false，未找到则为true
  const findData = await GoodsAttrConfig.findOrCreate({ where: { goods_id }, defaults: { goods_id, config: JSON.stringify(attr_list) } })
  console.log('updateAttrConfig--findData--%s==', JSON.stringify(findData));
  console.log('updateAttrConfig--attr_list--%s==', JSON.stringify(attr_list));
  if (!findData[1]) { // 找到已有记录 更新数据
    const res = await GoodsAttrConfig.update(
      { config: JSON.stringify(attr_list) },
      {
        where: { goods_id,  }
      })

    const attrValueResult = await bulkCreateGoodsAttr({ attr_list }, goods_id, store_id)
    console.log('GoodsAttrConfig.update--res--%s==', res);
    console.log('GoodsAttrConfig.update--attrValueResult: %s==', attrValueResult);
    return ctx.body = new ResBody({ data: res, code: 200, msg: '操作成功' })
  }
  // if (findData) {
  //   // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
  //   return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  // }
  // const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
  ctx.body = new ResBody({ data: findData, code: 200, msg: '操作成功' })
})

// 添加商品规格；
router.post("/addAttr", async ctx => {
  console.log('addAttr--%s--%s==', JSON.stringify(ctx), JSON.stringify(ctx.state.user));
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_id, store_id, attr_name, attr_values, status, is_delete = 0 } = ctx.query
  utils.checkParams({ goods_id, store_id, attr_name, attr_values })

  const findGoods = await Goods.findOne({ where: { goods_name, full_goods_name, store_id } })
  console.log('findGoods--%s==', findGoods);
  if (findGoods) {
    // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
    return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  }
  const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
  ctx.body = new ResBody({ data: goods })
})

router.get("/getManageBuildings", async ctx => {
  const { role, userId } = ctx.state.user
  const user = await User.findById(userId)
  let buildings = []
  switch (user.role) {
    case "superAdmin":
      buildings = await Building.findAll()
      break
    case "admin":
      buildings = await user.getBuildings()
      break
    default:
      buildings = []
      break
  }
  ctx.body = new ResBody({ data: { buildings, role } })
})

router.get("/getBuildingInfo", async ctx => {
  const { buildingId } = ctx.request.query
  const building = await Building.findOne({ where: { id: buildingId } })
  const result = building.toJSON()
  result.floorCount = await Floor.count({ where: { buildingId } })
  result.roomCount = await Room.count({ where: { buildingId } })
  result.studentCount = (
    await BuildingController.getStudents(buildingId)
  ).length
  ctx.body = new ResBody({ data: result })
})

router.post("/addBuildingWithRoom", async ctx => {
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { name, floorCount, roomCount } = ctx.request.body
  utils.checkParams({ name, floorCount, roomCount })
  const building = await Building.createBuilding({ name })
  // 为宿舍楼添加楼层
  for (let i = 1; i <= floorCount; i++) {
    const floor = await Floor.createFloor({ layer: i, buildingId: building.id })
    await Building.addFloor(building.id, floor)
    // 为楼层添加房间
    for (let j = 1; j <= roomCount; j++) {
      await Room.createRoom({
        number: i * 100 + j,
        floorId: floor.id,
        buildingId: building.id
      })
    }
  }
  ctx.body = new ResBody({ data: building })
})

router.del("/delBuilding", async ctx => {
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { id } = ctx.request.query
  const result = await BuildingController.delBuilding(id)
  ctx.body = new ResBody({ data: result })
})

router.get("/getAdminTableData", async ctx => {
  const { buildingId } = ctx.request.query
  utils.checkParams({ buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const admins = await building.getAdmins()
  ctx.body = new ResBody({ data: { admins, total: admins.length } })
})

router.get("/getCleanerTableData", async ctx => {
  const { buildingId } = ctx.request.query
  utils.checkParams({ buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const cleaners = await building.getCleaners()
  ctx.body = new ResBody({ data: { cleaners, total: cleaners.length } })
})

router.post("/addAdminToBuilding", async ctx => {
  const { adminAccount, buildingId } = ctx.request.body
  const admin = await User.findOne({
    where: { account: adminAccount, role: "admin" }
  })
  if (!admin) {
    throw new Error("找不到该用户")
  }
  const result = await Building.addAdmin(buildingId, admin.id)
  if (!result) {
    throw new Error("403-目标管理员已为当前宿舍楼的管理员，添加失败")
  }
  ctx.body = new ResBody({ data: { result } })
})

router.del("/removeBuildingAdmin", async ctx => {
  const { adminId, buildingId } = ctx.request.query
  utils.checkParams({ adminId, buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const admin = await User.findOne({ where: { id: adminId } })
  const result = await building.removeAdmin(admin)
  ctx.body = new ResBody({ data: { effectRow: result } })
})

module.exports = router.routes()
